/*
 * Copyright (c) 2014, FPX and/or its affiliates. All rights reserved.
 * Use, Copy is subject to authorized license.
 */
package pyip.lib.javaweb;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.support.RequestContext;

/**
 * 抽象的控制类
 * @author shiw 
 * 2014年12月10日
 */
public abstract class BaseController {
	
	@Autowired
	protected HttpServletRequest request;
	
	/**
	 * 获取国际化资源文件
	 * @param key 属性文件key
	 * @param args 替换占位符的参数
	 * @return
	 */
	protected String getText(String key, Object...args){
		return getProperty(this.request, key, args);
	}
	
	public static String getText(HttpServletRequest request, String key, Object...args){
		return getProperty(request, key, args);
	}

	private static String getProperty(HttpServletRequest request, String key, Object... args) {
		RequestContext requestContext = new RequestContext(request);
		String text = requestContext.getMessage(key, args);
		if(StringUtils.isBlank(text)){
			return key;
		}
		return text;
	}
	
	protected Result success(){
		return new Result();
	}
	
	protected Result success(Object data){
		return new Result(data);
	}
	
	protected Result error(String key, Object...objects){
		return Result.error(this.getText(key, objects));
	}
	
	protected Result error(String key, Object data){
		Result result = Result.error(this.getText(key));
		result.setData(data);
		return result;
	}
	
	protected Result saveSuccess(){
		return new Result(this.getText("msg.save.success"));
	}
	
	protected Result saveSuccess(Object data){
		Result resultModel = new Result(this.getText("msg.save.success"));
		resultModel.setData(data);
		return resultModel;
	}
	
	protected Result deleteSuccess(){
		return new Result(this.getText("msg.delete.success"));
	}
	
	protected Result deleteSuccess(Object data){
		Result resultModel = new Result(this.getText("msg.delete.success"));
		resultModel.setData(data);
		return resultModel;
	}
}
